<template>
  <div class="auto-reply-list">
    <div class="seach-box">
      <!-- 任务类型 -->
      <el-select v-model="tasktype" style="margin-right: 10px" size="small" clearable placeholder="请选择任务类型">
        <el-option v-for="type in types" :key="type.value" :label="type.label" :value="type.value"></el-option>
      </el-select>
      <!-- 任务状态 -->
      <el-select v-model="status" style="margin-right: 10px" size="small" clearable placeholder="请选择任务状态">
        <el-option v-for="item in states" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
      <el-button
        plain
        size="small"
        style="background-color: #ff9f00; color: #ffffff; border: solid #ff9f00 1px"
        @click="queryData"
      >
        开始搜索
      </el-button>
    </div>

    <!-- 号码列表 -->
    <el-table :data="tableData" stripe border>
      <el-table-column label="任务类型" :filters="taskTypes" prop="tasktype" :filter-method="filterTaskTypes">
        <template slot-scope="scope">
          <span v-text="tasktypeMap[scope.row.tasktype]"></span>
        </template>
      </el-table-column>
      <el-table-column label="消息类型">
        <template slot-scope="scope">
          <span v-text="restypeMap[scope.row.restype]"></span>
        </template>
      </el-table-column>
      <el-table-column label="当前状态" prop="state" width="80" :formatter="taskStateFormatter"></el-table-column>
      <el-table-column prop="remarks" label="备注"></el-table-column>
      <el-table-column label="预计执行时间" prop="execute_time"></el-table-column>
      <el-table-column label="实际执行时间" prop="update_time">
        <template slot-scope="scope">
          <span
            v-if="scope.row.update_time"
            v-text="$options.filters.transformTime2Minute(scope.row.update_time)"
          ></span>
          <span v-else v-text="'待执行'"></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template slot-scope="{ row }">
          <el-button v-if="row.state === 1" type="text" size="small" @click="modifyState(row, -1)">暂停</el-button>
          <el-button v-if="row.state === -1" type="text" size="small" @click="modifyState(row, 1)">继续</el-button>
          <el-button v-if="row.state === 1 || row.state === -1" type="text" size="small" @click="modifyState(row, 2)">
            取消
          </el-button>
          <el-button type="text" size="small" @click="deleteTask(row)">删除</el-button>
          <el-button type="text" size="small" @click="showTaskDetail(row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      style="margin: 10px auto 0"
      :current-page="pageNo"
      :page-sizes="[20, 40, 60, 80]"
      :page-size="pageSize"
      :pager-count="5"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>

    <!-- 任务详情 -->
    <el-dialog append-to-body class="task-detail-sort" title="任务详情" :visible.sync="taskDetailVisiable">
      <div
        style="width: 100%"
        :class="[
          {
            'chat-link': rowDetail.restype === 6
          },
          {
            'chat-app': rowDetail.restype === 13
          }
        ]"
        v-html="decodeChat(rowDetail)"
      ></div>

      <span slot="footer">
        <el-button size="medium" @click="taskDetailVisiable = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getTaskInfoList, taskDelete, updateTaskState } from '@/api/httpApi'
const imgError = require('@/assets/svg/conversation-image-error.svg')

export default {
  name: 'ToolsAutoTaskList',
  data() {
    return {
      tableData: [],
      tasktypeMap: {
        1: 'PC群发消息',
        2: 'PC发朋友圈',
        // 3: '删除好友',
        // 4: '删除群聊',
        5: '群发群消息',
        6: '批量加好友'
        // 7: '发朋友圈',
        // 8: '批量加好友'
      },
      restypeMap: {
        Text: 1,
        Picture: 2,
        Voice: 3,
        Video: 4,
        Link: 6,
        WeApp: 13,
        1: '文本',
        2: '图片',
        3: '语音',
        4: '视频',
        6: '链接',
        13: '小程序'
      },
      taskTypes: [
        { text: '群发好友', value: 1 },
        { text: '发朋友圈', value: 2 },
        { text: '群发群', value: 5 },
        { text: '批量加好友', value: 6 }
      ],
      types: [
        {
          value: 1,
          label: '群发好友'
        },
        {
          value: 5,
          label: '群发群'
        },
        {
          value: 6,
          label: '批量加好友'
        },
        {
          value: 2,
          label: '发朋友圈'
        }
      ], // 任务类型
      states: [
        {
          value: 0,
          label: '已完成'
        },
        {
          value: 1,
          label: '开启中'
        },
        {
          value: 2,
          label: '取消'
        },
        {
          value: -1,
          label: '暂停'
        }
      ], // 状态

      pageNo: 1, // 第几页
      pageSize: 20, // 每页几个数据
      tasktype: '', // 任务类型
      status: '', // 任务状态
      total: 0, // 当前页
      taskDetailVisiable: false,
      rowDetail: {} // 任务详情
    }
  },
  computed: {
    ...mapGetters({
      currentUser: 'currentUser'
    })
  },
  mounted() {
    this.queryData()
  },
  methods: {
    // 任务状态格式化
    taskStateFormatter(row) {
      const stateMap = {
        '-1': '暂停',
        0: '已完成',
        1: '开启中',
        2: '取消'
      }
      return stateMap[row.state]
    },
    // 查询
    queryData() {
      getTaskInfoList(
        this.currentUser.SupplierId,
        this.currentUser.UnionId,
        this.pageNo,
        this.pageSize,
        this.tasktype,
        this.status
      )
        .then((res) => {
          if (res.code === 0) {
            this.tableData = res.data.list || []
            this.total = res.data.total || 0
            // this.$message({
            //   type: 'success',
            //   message: '查询成功！',
            //   duration: 1000
            // })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    filterTaskTypes(value, row, column) {
      const property = column['property']
      return row[property] === value
    },
    // 修改pageSize
    handleSizeChange(val) {
      if (this.pageSize === val) return
      this.pageSize = val
      this.queryData()
    },
    // 修改当前页
    handleCurrentChange(val) {
      this.pageNo = val
      this.queryData()
    },
    showTaskDetail(row) {
      this.rowDetail = row
      this.taskDetailVisiable = true
    },
    // 修改任务状态
    modifyState(row, state) {
      updateTaskState(row.id, state).then((res) => {
        if (res.code === 0) {
          for (const gsl of this.tableData) {
            if (gsl.id === row.id) {
              gsl.state = state
              break
            }
          }
        }
      })
    },
    // 删除任务
    deleteTask(row) {
      taskDelete(row.id).then((res) => {
        if (res.code === 0) {
          this.$message.success('删除成功！')
          this.tableData = this.tableData.filter((x) => {
            return x.id !== row.id
          })
        }
      })
    },
    // 解析内容
    decodeChat(chat) {
      const content = chat.content
      const regJson = new RegExp(/^{.+}$/)
      let jContent = {}
      if (regJson.test(content)) {
        jContent = JSON.parse(content)
      }
      let thumb = ''
      let str = ''

      switch (chat.restype) {
        // 文本 1
        case 'Text':
        case 1:
          // return phiz.qqFaceImgMap(content)
          return content
        // 图片 2
        case 'Picture':
        case 2:
          return `<img class="chat-img" src="${content}"  alt="图片"/>`
        // 语音 3
        case 'Voice':
        case 3:
          if (content.endsWith('.amr')) {
            thumb = content.replace(/.amr$/, '.mp3')
          } else {
            thumb = content.replace(/.mp3:[0-9]+/, '.mp3')
          }
          return ` <audio src="${thumb}" alt="语音" controls></audio>`
        // 视频 4
        case 'Video':
        case 4:
          return `<video class="video-box" src="${content}" type="video/mp4" alt="视频" controls></video>`
        // 链接消息 6
        case 'Link':
        case 6:
          str = `
                        <span class="link-title">${jContent.Title}</span>
                        <div class="link-content">
                          <span class="link-des">${jContent.Des}</span>
                          <img class="link-img" src="${jContent.Thumb}" alt="链接图片" />
                        </div>
                        <div class="link-type">${jContent.TypeStr}</div>
                        `
          return str

        // 小程序 13
        case 'WeApp':
        case 13: {
          let appIcon = imgError
          let appSource = '无效小程序'
          let appTitle = '无效小程序'
          let appThumb = ''
          let appTypeStr = '小程序'
          if (typeof content === 'string' && regJson.test(content)) {
            jContent = JSON.parse(content)
            appIcon = jContent.Icon && typeof jContent.Icon !== 'undefined' ? jContent.Icon : imgError
            appSource = jContent.Source
            appTitle = jContent.Title || jContent.Des
            appThumb = jContent.Thumb
            appTypeStr = jContent.TypeStr ? jContent.TypeStr : '小程序'
          }

          str = `
                  <div class="app-des">
                  <img class="app-icon" src="${appIcon}" alt="icon" />
                  <span class="app-source ellipsis">${appSource}</span>
                  </div>
                  <div class="app-title ellipsis">${appTitle}</div>
                  <img class="app-img" src="${appThumb}" />
                  <div class="app-typestr">${appTypeStr}</div>
                   `
          return str
          // return jContent
        }

        // 不支持的消息
        default:
          return chat.content
        // return `不支持的消息类型${chat.ContentType}`
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.auto-reply-list {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 10px 20px;

  .seach-box {
    padding-bottom: 10px;
  }
}
</style>
